package cn.it.shop.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

/*
 *  用来处理权限越界处理类,主要是区分HTTP请求和ajax请求的处理
 * */
@Component("accessDeniedHandler")
public class AjaxAccessDeniedHandler implements AccessDeniedHandler {
	
	private String deniedPath="/alogin.jsp";

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
		System.out.println(request.getHeader("X-Requested-With"));
		if (isAjax) {
			// 如果是ajax请求
			response.setCharacterEncoding("UTF-8");
			PrintWriter writer = response.getWriter();
			writer.write("访问权限越界!");
			writer.flush();
			writer.close();
		} else {
			// 如果是http请求
			request.getSession().setAttribute("error", "访问权限越界!");
			response.sendRedirect(request.getContextPath() + deniedPath);
		}

	}

}
